package com.example.nutritionmanager.data

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.nutritionmanager.ai.Message
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

// 新增消息数据存储类
@Singleton
class ChatDataStore @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private val Context.dataStore by preferencesDataStore(name = "chat_store")
    private val CHAT_HISTORY = stringPreferencesKey("chat_history")
    private val gson = Gson()

    // 保存聊天记录
    suspend fun saveChat(messages: List<Message>) {
        context.dataStore.edit { preferences ->
            preferences[CHAT_HISTORY] = gson.toJson(messages)
        }
    }

    // 读取聊天记录
    val chatHistory: Flow<List<Message>> = context.dataStore.data
        .map { preferences ->
            val json = preferences[CHAT_HISTORY] ?: return@map emptyList()
            gson.fromJson(json, object : TypeToken<List<Message>>() {}.type)
        }
}